// pages/yuecha/yuecha.js
import {toast} from "../../utils/tool";

const app = getApp();

function formatTime(time) {
    const date = new Date(time)
    const [year, month, day] = [date.getFullYear(), date.getMonth() + 1, date.getDate()]
    const [h, m] = [date.getHours(), date.getMinutes()]
    return `${month}月${day}日 ${h < 10 ? '0' + h : h}:${m < 10 ? '0' + m : m}`
}

function getMaxDate() {
    const date = new Date()
    const y = date.getFullYear()
    return new Date(y, 11, 30).getTime()
}

const initDayCol = () => {
    const r = []
    for (let i = 1; i <= 24; i++) {
        r.push({
            label: `${i}小时`,
            value: i
        })
    }
    return r
}

Page({
    /**
     * 页面的初始数据
     */
    data: {
        starList: [],
        imgList: [],
        current: 1,
        showStarTime: false,
        dayColumn: initDayCol(),
        endTimeLabel: '',
        startTimeValue: 0,
        sexEnum: {
            1: '男',
            2: '女',
        },
        visible: false,
        list: {},
        shijian: {},
        storelist: [],
        show: false,
        show1: false,
        showTime: false,
        total: 0,
        hour: 0,
        columns: [{
            values: ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00'],
            defaultIndex: 2
        },
            // 第二列
            {
                values: ['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00'],
                defaultIndex: 1
            }
        ],
        store_name: '', //茶室名字
        time_range: '', //时间段
        master_id: '', //茶艺师id
        store_id: '', //店铺id
        start_time: '', //开始时间
        end_time: '', //结束时间
        allprice: 0, //总共花费价格 = 预约时长 * 每小时单价
        shichang: 0, //时长
        endshow: '', //结束时间
        currentDate: new Date().getTime(),
        hasSelect: false,
        minDate: new Date().getTime(),
        endTimeCurrent: new Date().getTime(),
        showEndTime: false,
        endMinDate: new Date().getTime(),
        maxDate: getMaxDate(),
        startTime: '',
        endTime: '',
        storeList: [],
        storeIndex: -1,
        activeStoreName: '',
        filter(type, options) {
            if (type === 'minute') {
                return options.filter((option) => option % 30 === 0);
            }

            return options;
        },
        formatter(type, value) {
            if (type === 'year') {
                return `${value}年`;
            }
            if (type === 'month') {
                return `${value}月`;
            }
            if (type === 'day') {
                return `${value}日`;
            }
            if (type === 'hour') {
                return `${value}时`;
            }
            if (type === 'minute') {
                return `${value}分`;
            }
            return value;
        },
        start: '', //开始时间
        end: '' //结束时间
    },
    swiperChange(ev) {
        const {current} = ev.detail
        this.setData({
            current: current + 1
        })
    },
    closeStartTimeHand() {
        this.closeStarTime()
    },

    closeStarTime(ev) {
        this.setData({
            showStarTime: false,
        })
    },

    closeEndTime() {
        this.setData({
            showEndTime: false
        })
    },
    startTimeConfirm(ev) {
        const {detail} = ev
        const time = formatTime(detail)
        this.setData({
            currentDate: detail,
            startTime: time,
            showStarTime: false,
            startTimeValue: detail,
            hasSelect: true,
        })
        this.initEndTime(detail)
    },

    endTimeConfirm(ev) {
        const {list} = this.data
        const {value} = ev.detail
        const {value: v, label} = value
        this.setData({
            showEndTime: false,
            hour: v,
            endTimeLabel: label,
            total: list.price * v,
        })
    },

    choseEndTimeHand() {
        const {hasSelect} = this.data
        if (!hasSelect) return toast({title: '请选择开始时间'})
        this.setData({
            showEndTime: true,
        })
    },

    initEndTime(time) {
        const currentTime = new Date(time + 60 * 60 * 1000 * 2).getTime()
        this.setData({
            endTimeCurrent: currentTime,
            endMinDate: currentTime,
        })
    },

    orderConfirm() {
        const hasMobile = app.checkHasMobile()
        if (!hasMobile) return

        var shichang = this.data.shichang,
            master_id = this.data.master_id,
            store_id = this.data.store_id,
            start_time = this.data.startTime,
            end_time = this.data.endTime,
            allprice = this.data.allprice,
            // allprice = '0.01',
            num = this.data.num;

        const {storeIndex, hour, startTime, startTimeValue, total} = this.data
        const endTime = startTimeValue + (1000 * 60 * 60 * hour)

        function getTime(value) {
            const date = new Date(value)
            const [year, month, day, hour, minute] = [date.getFullYear(), date.getMonth() + 1, date.getDate(), date.getHours(), date.getMinutes()]
            return `${year}-${month < 10 ? '0' + month : month}-${day < 10 ? '0' + day : day} ${hour < 10 ? '0' + hour : hour}:${minute < 10 ? '0' + minute : minute}`
        }

        if (storeIndex === -1) return toast({title: '请选择茶室'})
        if (!this.data.hasSelect) return  toast({title:'请选择预约时间'})
        if (!this.data.hour) return  toast({title:'请选择时长'})
        const targetStore = this.data.storeList[this.data.storeIndex]
        app.ajax({
            url: '/api/user/postMasterOrder',
            data: {
                master_id: master_id,
                store_id: targetStore.id,
                start_time: getTime(startTimeValue),
                end_time: getTime(endTime),
                allprice: total,
                shichang: hour,
            },
            success: res => {
                if (res.code == 1) {
                    wx.redirectTo({
                        url: '/pages/cys_order/cys_order?order_id=' + res.data.id
                    })
                } else {
                    wx.showToast({
                        title: res.msg,
                        icon: 'none'
                    });
                }
            }
        }, 1)
    },

    onFinish(ev) {
        console.log(ev)
    },
    choseTimeCancel() {
        this.setData({
            showTime: false,
        })
    },
    // timePickerChange(event) {
    //     const {picker, value, index} = event.detail;
    //     picker.setColumnValues(1, citys[value[0]]);
    // },
    // choseTimeConfirm(ev) {
    //
    // },
    onClose() {
        this.setData({
            visible: false
        })
    },
    pickerClose() {
        this.onClose()
    },

    choseTimeHand() {
        this.setData({
            showStarTime: true
        })
    },
    pickerConfirm(ev) {
        const {index, value: {name}} = ev.detail
        this.setData({
            storeIndex: index,
            activeStoreName: name
        })
        this.onClose()
    },

    choseStoreHand() {
        this.setData({
            visible: true
        })
    },
    call(e) {
        if (this.data.list.is_tel == 2) {
            wx.showToast({
                title: '请先预订茶室，茶室订好的直接拨打电话',
                icon: 'none'
            })
            return
        }
        let tel = e.currentTarget.dataset.phone
        wx.makePhoneCall({
            phoneNumber: tel,
            success: function () {
            },
        })
    },
    // 创建订单页面
    unsettled: function () {
        // var shichang = this.data.shichang,
        //     master_id = this.data.master_id,
        //     store_id = this.data.store_id,
        //     start_time = this.data.start_time,
        //     end_time = this.data.end_time,
        //     allprice = this.data.allprice,
        //     num = this.data.num;
        // if (this.data.store_id == '') {
        //     wx.showToast({
        //         title: '请选择预定茶室',
        //         icon: 'none'
        //     });
        //     return false;
        // }
        // if (num <= 0) {
        //     wx.showToast({
        //         title: '预定时间1小时起',
        //         icon: 'none'
        //     });
        //     return false;
        // }
        // app.ajax({
        //     url: '/api/user/postMasterOrder',
        //     data: {
        //         master_id: master_id,
        //         store_id: store_id,
        //         start_time: start_time,
        //         end_time: end_time,
        //         allprice: allprice,
        //         shichang: shichang,
        //     },
        //     success: res => {
        //         console.log(res)
        //         if (res.code == 1) {
        //             wx.navigateTo({
        //                 url: '/pages/cys_order/cys_order?order_id=' + res.data.id
        //             })
        //         } else {
        //             wx.showToast({
        //                 title: res.msg,
        //                 icon: 'none'
        //             });
        //         }
        //     }
        // }, 1)
    },
    onConfirm(event) {
        console.log(event.detail, event)
        var date = new Date(event.detail);
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
        var h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
        var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes());
        var s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());

        console.log(Y + M + D + h + m);
        let start = Y + M + D + h + m
        let time = event.detail / 1000
        console.log(this.data.shijian, time)

        if (time > this.data.shijian.jiezhi) {
            wx.showToast({
                title: '茶艺师需提前一个小时预约',
                icon: 'none'
            })
            return
        }
        this.setData({
            start_time: event.detail,
            show: false,
            start: start
        })
    },
    onConfirm2(event) {
        console.log(event.detail, event)
        var date = new Date(event.detail);
        var Y = date.getFullYear() + '-';
        var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        var D = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()) + ' ';
        var h = (date.getHours() < 10 ? '0' + (date.getHours()) : date.getHours()) + ':';
        var m = (date.getMinutes() < 10 ? '0' + (date.getMinutes()) : date.getMinutes());
        var s = (date.getSeconds() < 10 ? '0' + (date.getSeconds()) : date.getSeconds());
        console.log(Y + M + D + h + m);
        let end = Y + M + D + h + m
        let number = parseInt(event.detail - this.data.start_time)
        console.log(number / 1000 / 60 / 60)
        let num = number / 1000 / 60 / 60
        if (num < 1) {
            wx.showToast({
                title: '茶艺师预约时间一个小时起',
                icon: "none"
            })
            return
        }
        this.setData({
            end_time: event.detail,
            endshow: false,
            end: end,
            shichang: num,
            allprice: num * this.data.list.price
        })


    },
    onConfirm1(event) {
        const {
            picker,
            value,
            index
        } = event.detail;
        this.setData({
            show1: false,
            store_id: value.id,
            store_name: value.name
        })
    },
    onCancel() {
        this.setData({
            show: false
        })
    },
    onCancel1() {
        this.setData({
            endshow: false, show1: false
        })
    },
    onChange(event) {

    },
    teatime() {
        if (this.data.list.is_tel == 2) {
            wx.showToast({
                title: '请先预订茶室，茶室订好再预定茶艺师',
                icon: 'none'
            })
            return
        }
        this.setData({
            show: true
        })
    },
    teaendtime() {
        if (this.data.list.is_tel == 2) {
            wx.showToast({
                title: '请先预订茶室，茶室订好再预定茶艺师',
                icon: 'none'
            })
            return
        }
        this.setData({
            endshow: true
        })
    },
    onInput() {
    },
    tearoom() {
        if (this.data.list.is_tel == 2) {
            wx.showToast({
                title: '请先预订茶室，茶室订好再预定茶艺师',
                icon: 'none'
            })
            return
        }
        this.setData({
            show1: true
        })
    },


    shareHandler() {

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        this.data.master_id = options.id;
        let self = this
        wx.getLocation({
            type: 'wgs84',
            success(res) {
                // const latitude = res.latitude
                // const longitude = res.longitude
                // const speed = res.speed
                // const accuracy = res.accuracy
                app.ajax({
                    url: '/api/user/getMasterInfo',
                    data: {
                        master_id: options.id,
                        user_lat: res.latitude,
                        user_lon: res.longitude
                    },
                    success: res => {
                        const {storelist, masterinfo, information} = res.data
                        let current = 1
                        let imgList = []
                        const {information: _imgList, weight, height, address} = information
                        if (!!_imgList) {
                            imgList = _imgList.split(',').filter(Boolean)
                        }
                        let {avatar, star} = masterinfo
                        if (!avatar.includes('https')) {
                            masterinfo.avatar = `https://sanju.xinyunweb.com${avatar}`
                        }
                        star = Number(star)
                        if (isNaN(star)) {
                            star = 0
                        }
                        const starList = []
                        for (let i = 0; i < 5; i++) {
                            const isStar = i < star
                            starList.push({
                                url: isStar ? '/assets/cha/star.png' : '/assets/cha/star-filled.png'
                            })
                        }
                        masterinfo.height = height || '-'
                        masterinfo.weight = weight || '-'
                        masterinfo.address = address || '-'
                        self.setData({
                            starList,
                            imgList,
                            current,
                            shijian: res.data.shijian,
                            list: masterinfo,
                            // storelist: res.data.storelist
                            storeList: storelist,
                        })
                    }
                });
            }
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {
        const {master_id} = this.data
        return {
            title: '初见',
            path: '/pages/yuyue/yuyue?id=' + master_id
        }
    }
})
